package com.zxc.shortlink.component.data;

import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
* @author zxc_user
* @date 2022/3/24 15:00
* @version 1.0
* @description 短链接布隆过滤器数据
**/
@Component
public class ShortLinkComponentData {

    @Resource
    private RedissonClient redissonClient;
    private RBloomFilter<String> bloomFilter;

    @PostConstruct
    public void init() {
        bloomFilter = redissonClient.getBloomFilter("shortLink");
        //初始化布隆过滤器：预计元素为100000000L,误差率为3%
        bloomFilter.tryInit(100000000L,0.03);
    }

    /**
     * 设置数据
     * @param dataList
     */
    public void setData(List<String> dataList) {
        if(dataList != null) {
            for (String data : dataList) {
                bloomFilter.add(data);
            }
        }
    }

    /**
     * 添加一个数据
     * @param data
     */
    public void addData(String data) {
        if(data != null) {
            setData(Collections.singletonList(data));
        }
    }

    /**
     * 是否在当前系统中存在
     * @param shortLink
     * @return
     */
    public boolean matches(String shortLink) {
        return bloomFilter.contains(shortLink);
    }
}
